<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.jz_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-download" @click="handleDownloadExcel" :loading="tempLoading">{{ tempLoading ? '下载中' : '下载模板' }}</el-button>
        <el-button size="small" type="primary" icon="el-icon-upload" @click="importVisible = true">一键导入</el-button>
      </template>
      <template slot-scope="{type,size,row,index}" slot="menu">
        <el-button icon="el-icon-start" :size="size" :type="type" @click="xsVisibled(row)">学生列表</el-button>
      </template>
    </avue-crud>
    <el-dialog title="学生列表" :visible.sync="xsVisible">
      <jzxslist v-bind:jzId="jzId" ref="xsList"/>
    </el-dialog>
    <el-dialog title="一键导入家长学生信息" :visible.sync="importVisible">
      <avue-form ref="avueform" v-model="importForm" :option="formOption" :upload-before="patriarchbefore"></avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, add, update, remove, uploadPatriarchInfo } from "@/api/service/jz";
import {mapGetters} from "vuex";
import jzxslist from "@/views/service/jzxslist";
import { cardids, isMobile } from "@/util/validate";
import { grade } from "@/api/service/xs";
import { getSchoolTree } from "@/api/platform/psychologyQuestionnaire";

export default {
  components: {jzxslist},
  data() {
    return {
      xsVisible: false,
      jzId: '0',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuType: 'menu',
        menuBtnTitle: '更多操作',
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "学校名称",
            prop: "schoolId",
            search: true,
            // hide: true,
            rules: [{
              required: true,
              message: "请输入学校名称",
              trigger: "blur"
            }],
            type: "tree",
            dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
            // cascader: ['jdId', 'xqId'],
            props: {
              label: "xxName",
              value: "id"
            },
            // change: ({value}) => {
            //   this.schoolTypeChange(value);
            // }
          },
          {
            label: "家长姓名",
            prop: "jzName",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入家长姓名",
              trigger: "blur"
            }],
            maxlength: 50,
            showWordLimit: true
          },
          {
            label: "家长电话",
            prop: "jzPhone",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入家长电话",
              trigger: "blur"
            }],
            formatter: (val) => {
              var len = val.jzPhone.length - 3 - 2;
              var xing = '';
              for (var i = 0; i < len; i++) {
                xing += '*';
              }
              return val.jzPhone.substring(0, 3) + xing + val.jzPhone.substring(val.jzPhone.length - 2)
            },
            maxlength: 11,
            showWordLimit: true
          },

          // {
          //   label: "身份类型",
          //   prop: "jzIdType",
          //   overHidden:true,
          //   rules: [{
          //     required: false,
          //     message: "请输入身份类型",
          //     trigger: "blur"
          //   }],
          //   type: 'select',
          //   dicUrl: "/api/PcPublicService/GetDictionaryList?code=SHENGFENLEIXING",
          //   props: {
          //     label: "dictValue",
          //     value: "dictKey"
          //   },
          //   dataType: "number",
          // },
          {

            label: "身份号码",
            prop: "jzIdNo",
            search: true,
            maxlength: 18,
            showWordLimit: true,
            rules: [{
              required: true,
              message: "请输入身份号码",
              trigger: "blur"
            }],
            formatter: (val) => {
              var len = val.jzIdNo.length - 6 - 2;
              var xing = '';
              for (var i = 0; i < len; i++) {
                xing += '*';
              }
              return val.jzIdNo.substring(0, 6) + xing + val.jzIdNo.substring(val.jzIdNo.length - 2)
            }
          },
          {
            label: "家长地址",
            prop: "jzAddress",
            span: 24,
            rules: [{
              required: true,
              message: "请输入家长地址",
              trigger: "blur"
            }],
            overHidden: true,
            maxlength: 200,
            showWordLimit: true
          },
          {
            label: "头像",
            prop: "jzPic",
            rules: [{
              required: true,
              message: "请选择头像",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            // fileSize: 520,
            accept: "image/*",
            listType: 'picture-img',
            span: 24,
            propsHttp: {
              url: 'link',
              name: 'name',
              res: 'data'
            },
            action: '/api/localfiles/uploadPcFile',
            tip: '只能上传jpg/png文件，且不超过500kb',
            hide: true
          },
        ]
      },
      data: [],
      tempLoading: false,
      importLoading: false,
      importVisible: false,
      formOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
        {
            label: "学校",
            prop: "schoolId",
            type: 'tree',
            dicData: [],
            rules: [
              {
                required: true,
                message: "请选择学校",
                trigger: "blur"
              }
            ],
            props: {
              label: "xxName",
              value: "id"
            },
            cascader: ['jdId'],
            change: ({value}) => {
              this.schoolTypeChange(value);
            }
          },
          {
            label: "所属阶段",
            prop: "jdId",
            type: "select",
            overHidden: true,
            rules: [{
              required: true,
              message: "请选择所属阶段",
              trigger: "blur"
            }],
            hide: true,
            dicUrl: "/api/ManageStudent/GetSchoolStageSelect",
            cascader: ['njId'],
            props: {
              label: "title",
              value: "id"
            },
            change: ({value}) => {
              this.jdIdTypeChange(value);
            }
          },
          {
            label: "年级",
            prop: "njId",
            type: "select",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入年级名称",
              trigger: "blur"
            }],
            props: {
              label: "title",
              value: "id"
            },
            cascader: ['bjId'],
            dicData: []
          },
          {
            label: "班级",
            prop: "bjId",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入班级",
              trigger: "blur"
            }],
            type: "select",
            dicUrl: "/api/ManageStudent/GetClassSelect?njId={{key}}",
            props: {
              label: "bjName",
              value: "id"
            },
          },
          {
            label: '信息上传',
            prop: 'importInfo',
            type: 'upload',
            multiple: false,
            span: 24,
            propsHttp: {
              url:'url',
              name:'name',
              res: 'data'
            },
            accept: ['.xls', '.xlsx'],
            fileText: '点击上传并提交',
            rules: [{
              required: true,
              message: "请选择文件上传",
              trigger: "blur"
            }],
            showFileList: false
          },
        ],
      },
      schoolId: '',
      importForm: {}
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.jz_add, false),
        viewBtn: this.vaildData(this.permission.jz_view, false),
        delBtn: this.vaildData(this.permission.jz_delete, false),
        editBtn: this.vaildData(this.permission.jz_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    this.getTree()
  },
  methods: {
    patriarchbefore(res, done) {
      this.$confirm('上传后不得修改，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let fd = new FormData()
        fd.append('file', res)
        fd.append('schoolId', this.importForm.schoolId)
        fd.append('jdId', this.importForm.jdId)
        fd.append('njId', this.importForm.njId)
        fd.append('bjId', this.importForm.bjId)
        // {
        //   file: fd,
        //   schoolId: this.importForm.schoolId,
        //   njId: this.importForm.njId,
        //   jdId: this.importForm.jdId,
        //   bjId: this.importForm.bjId
        // }
        uploadPatriarchInfo(fd).then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })
          this.importVisible = false
          this.$refs.avueform.resetForm()
        })
        done()
      }).catch(() => {
        done()
      })
    },
    handleDownloadExcel() {
      const a = document.createElement("a")
      a.href = 'https://ossdata.kaibujiaoyu.com/template/ParentStudentInfoTemplate.xlsx'
      a.setAttribute('download', "家长信息模板")
      a.click()
      document.body.removeChild(a)
    },
    getTree() {
      getSchoolTree().then(res => {
        const column = this.findObject(this.formOption.column, "schoolId");
        column.dicData = res.data.data;
      })
    },
    schoolTypeChange(v) {
      this.schoolId = v
    },
    // 切换所属阶段
    jdIdTypeChange(v) {
      if (this.schoolId !== "" && this.schoolId !== null && this.schoolId !== undefined) {
        let params = {
          schoolId: this.schoolId,
          jdId: v
        }
        grade(params).then(res => {
          const gradeData = this.findObject(this.formOption.column, "njId");
          gradeData.dicData = res.data.data
        });
      }
    },
    xsVisibled(row) {
      this.xsVisible = true;

      if (this.jzId !== '0') {
        this.jzId = row.id;
        this.$refs.xsList.onLoad({
          currentPage: 1, pageSize: 10
        }, {
          jzId: this.jzId
        });
      } else {
        this.jzId = row.id;
      }


    },
    rowSave(row, done, loading) {
      if (!isMobile(row.jzPhone)) {
        this.$message({
          type: "warning",
          message: "请输入正确手机号!"
        });
        loading();
        return 0
      }
      if (!cardids(row.jzIdNo)) {
        this.$message({
          type: "warning",
          message: "请输入正确身份证号!"
        });
        loading();
        return 0
      }
      row.id = row.id === '' ? '0' : row.id
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (!isMobile(row.jzPhone)) {
        this.$message({
          type: "warning",
          message: "请输入正确手机号!"
        });
        loading();
        return 0
      }
      if (!cardids(row.jzIdNo)) {
        this.$message({
          type: "warning",
          message: "请输入正确身份证号!"
        });
        loading();
        return 0
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: this.ids});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
